package com.zzyl.job;


import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

//启动数据过滤
// 设备上报数据报警规则过滤
@Component
public class AlertJob {
    @Autowired(required = false)
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private AlertRuleService alertRuleService;

    /**
     * 设备上报数据报警规则过滤<br>
     * 周期：每分钟执行一次
     */
    @Scheduled(cron = "0/30 * * * * ? ")
    public void deviceDataAlertFilter() {
        //查询所有规则
     List<AlertRule> alertRules = alertRuleMapper.selectByFunctionId(null,
             null, null);
         //判断规则是否为空
         if(EmptyUtil.isNullOrEmpty(alertRules)){
               return;
         };
         //非空
         //查询所有设备上报的数据 ，去redis里面
         List<Object> values = redisTemplate.opsForHash().values
                 (CacheConstants.DEVICE_LASTDATA_CACHE_KEY);
         if(EmptyUtil.isNullOrEmpty(values)){
            return;
         }
         List<DeviceDataVo> list=new ArrayList<>();
         //非空 ,进行遍历
//        for (Object value : values) {
//             List<DeviceDataVo> list1 = JSONUtil.toList(value.toString(), DeviceDataVo.class);
//             list.addAll(list1);
//        }
        values.forEach(json ->
                list.addAll(JSONUtil.toList(json.toString(), DeviceDataVo.class)));
        //判断是否为空
        if(EmptyUtil.isNullOrEmpty(list)){
            return;
        }
        //非空
        //数据格式标准化处理
        list.forEach(deviceDataVo -> {
            alertRuleService.deviceDataAlertFilter(deviceDataVo);
        });

    }



}
